package com.glor.operation.common.web.security.filter;

import com.glor.operation.common.excep.InvalidKaptchaException;
import com.google.code.kaptcha.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by heylear.cai on 2016/2/19.
 */
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String requestKaptcha = request.getParameter("kaptcha");
        String kaptcha = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (StringUtils.isEmpty(requestKaptcha)){
            throw new InvalidKaptchaException("验证码不能为空");
        }
        if (!requestKaptcha.trim().equalsIgnoreCase(kaptcha)){
            throw new InvalidKaptchaException("验证码不正确");
        }
        try {
            return super.attemptAuthentication(request, response);
        } catch (BadCredentialsException e){
            throw new BadCredentialsException("用户名或密码不正确");
        }
    }
}
